package com.example.worklab.edittext.clearedittext

import android.content.Context
import android.content.res.Resources
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.appcompat.widget.AppCompatEditText
import com.example.worklab.R

class ClearEditText @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatEditText(context, attrs, defStyleAttr) {

    private var clearIcon: Drawable?
    private var clearIconSize: Int?

    init {
        val a = context.obtainStyledAttributes(attrs, R.styleable.ClearEditText)
        clearIcon = a.getDrawable(R.styleable.ClearEditText_clearIcon)

        clearIconSize =
            a.getDimension(R.styleable.ClearEditText_clearIconSize, 20.toPx().toFloat()).toInt()

        a.recycle()

        requestFocus()
    }

    override fun onTextChanged(
        text: CharSequence?,
        start: Int,
        lengthBefore: Int,
        lengthAfter: Int
    ) {
        super.onTextChanged(text, start, lengthBefore, lengthAfter)
        setDeleteIconVisible(hasFocus() && length() > 0)
    }

    override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect)
        setDeleteIconVisible(focused && length() > 0)
    }

    private fun setDeleteIconVisible(clearIconVisible: Boolean) {
        clearIcon?.setBounds(0, 0, clearIconSize ?: 0, clearIconSize ?: 0)
        setCompoundDrawables(null, null,  if (clearIconVisible) clearIcon else null, null)
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        when (event?.action) {
            MotionEvent.ACTION_UP -> {
                clearIcon?.let {
                    if (isTouchClearIcon(event.x, event.y)) {
                        setText("")
                    }
                }
            }

            else -> {}
        }
        return super.onTouchEvent(event)
    }

    /**
     * 判断是否点击了删除图标
     */
    private fun isTouchClearIcon(x: Float, y: Float) = clearIcon?.let {
        x <= width - paddingEnd && x >= width - paddingEnd - it.bounds.width()
    } ?: false

    private fun Int.toDp() = px2dp(this.toFloat())

    private fun px2dp(pxValue: Float): Int {
        val scale = Resources.getSystem().displayMetrics.density
        return (pxValue / scale + 0.5f).toInt()
    }

    private fun Int.toPx() = dp2px(this.toFloat())
    private fun dp2px(dpValue: Float): Int {
        val scale = Resources.getSystem().displayMetrics.density
        return (dpValue * scale + 0.5f).toInt()
    }
}